<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class CommentController extends Controller
{
    //发表评价
    public function create()
    {

    }

    public function index($id)
    {
        $data = DB::table('comment')->where('pro_id',$id)->get();
        foreach($data as $value)
        {
            $pro = DB::table('product')-> select('keyword')-> where('product_id',$value->pro_id)->first();
            $value -> keyword = $pro ->keyword;
            $res = DB::table('member')-> select('nickname','pic','permission')-> where('member_id',$value->mem_id)->first();
            $value-> nickname = $res->nickname;
            $value-> pic = $res-> pic;
            if($res->permission==1)
            {
                $value->permission = '普通会员';
            }else if($res->permission==2) {
                $value->permission = '超级会员';
            }else{
                $value->permission = '超级会员';
            }
        }
        $arr['good'] = DB::table('comment')->select('score')->where('score','>',80)->count();
        $arr['well'] = DB::table('comment')->select('score')->where('score','>',60)->where('score','<=',80)->count();
        $arr['count'] = count($data);
        $arr['bad'] = $arr['count'] - $arr['well'] - $arr['good'];
        //        dd($data);
        return view('/comment/take/edit',['data'=>$data,'id'=>$id,'arr'=>$arr]);
    }
    //
    //收货评价
    public function edit($id)
    {
        $mem_id = session('member_id');
        $data = DB::table('order')
            ->where('mem_id','=',$mem_id)
            ->where('order_id',$id)
            ->first();
        $data -> res = DB::table('order_details')
            ->where('ord_id',$data -> order_id)
            ->get();
        return view('/home/myhouse/comment/edit',['data'=>$data]);
    }

    public function show(Request $request)
    {
        $data = $request->except('_token');
        $this->validate($request, [
            //验证规则，required(不为空)
            'content' => 'required',
            'score' => 'required',
        ],[
            //错误提醒
            'content.required' => '请输入评价内容',
            'score.required' => '请点击评分',
        ]);
        $data['score'] = $data['score']*20;
        $data['ptime'] = time();
        $data['mem_id']=session('member_id');
        $pro_id = $data['pro_id'];
        $res = DB::table('comment')->insert($data);
//        dd($res);
        if($res)
        {
            return redirect("/home/myhouse/order/show/$pro_id")-> with(['success'=>'评价成功']);
        }else{
            return back()->with(['error','评论失败']);
        }
    }
}
